package show.me.the.money.util.exp;

import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import show.me.the.money.util.context.Context;

@SuppressWarnings("unchecked")
public class ExpRunner {
	private static Log logger = LogFactory.getLog(ExpRunner.class);
	private static HashMap<String,Expression> flyweight = new HashMap<String,Expression>();
	private static ObjectMapper jsonMapper = new ObjectMapper();
	
	public static void register(String name,Expression exp){
		flyweight.put(name, exp);
	}
	
	public void setExpressions(HashMap<String, Expression> exps){
		flyweight = exps;
	}
	
	private static Expression getExp(String name){ 
		if (!flyweight.containsKey(name)){
			logger.fatal("exp not found:" + name);
			return null;
		}
		Expression exp = flyweight.get(name);
		return exp;
	}
	
	public static Object run(String s,Context oCtx){
		try {
			List lsExp = jsonMapper.readValue(s, List.class);
			return run(lsExp,oCtx);
		} 
		catch (Exception e) {
			logger.fatal("run JSONException:", e);
		}
		return null;
	}
	
	public static Object run(List lsExp,Context ctx){
			String name;
			try {
				name = (String)lsExp.get(0);
				Expression exp = getExp(name);
				if(exp != null){
					return exp.run(lsExp,ctx);
				}
			} catch (Exception e) {
				logger.fatal("run JSONException:", e);
			}
			return null;
	}
	
	public static String toString(String s,Context ctx){
			try {
				List lsExp = jsonMapper.readValue(s, List.class);
				return toString(lsExp,ctx);
			} 
			catch (Exception e) {
				logger.fatal("toString JSONException:", e);
			}
			return "";
	
	}
	
	public static String toString(List lsExp,Context ctx) {
		String name;
		try {
			name = (String)lsExp.get(0);
			Expression exp = getExp(name);
			if(exp != null){
				return exp.toString(lsExp,ctx);
			}
		} catch (Exception e) {
			logger.fatal("toString JSONException:" , e);
		}
		return "";
	}
}
